package com.mooc.lib_video.ui.detail

import android.text.Editable
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.mooc.ijk.widget.IJKView
import com.mooc.lib_common.arouter.service.UserLoginAService
import com.mooc.lib_common.model.FeedEntity
import com.mooc.lib_common.mvvm.BaseActivity
import com.mooc.lib_network.imgload.ImageLoad
import com.mooc.lib_video.BR
import com.mooc.lib_video.R
import com.mooc.lib_video.adapter.CommentsAdapter
import com.mooc.lib_video.databinding.ActivityDetailBinding
import com.tb.emoji.Emoji
import com.tb.emoji.EmojiUtil
import com.tb.emoji.FaceFragment
import com.tb.emoji.FaceFragment.OnEmojiClickListener
import java.io.IOException

@Route(path = "/lib_video/DetailActivity")
class DetailActivity : BaseActivity<DetailViewModel, ActivityDetailBinding>(),
    View.OnClickListener,OnItemChildClickListener, OnEmojiClickListener{
    lateinit var entity : FeedEntity
    lateinit var commentsAdapter: CommentsAdapter

    override fun initView() {
        entity = intent.getParcelableExtra<FeedEntity>("item") as FeedEntity
        v.detailClose.setOnClickListener(this)
        vm.itemId = entity.itemId
        val userEntity = (ARouter.getInstance().build("/lib_user/UserLoginService").
        navigation() as UserLoginAService).getUser()
        vm.userId = userEntity!!.userId.toLong()
        v.setVariable(BR.vm, vm)
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        commentsAdapter = CommentsAdapter()
        commentsAdapter.setOnItemChildClickListener(this)
        v.detailComments.layoutManager = manager
        v.detailComments.adapter = commentsAdapter
        //区分跳转进来的内容为图片详情或视频详情
        if (entity.itemType == 1){
            //图片
            v.detailPlayerView.setConverPath(entity.cover!!)
        }else{
            //视频
            v.detailPlayerView.setPath(entity.url!!)
        }
        ImageLoad.loadMatch(entity.author!!.avatar, v.avatar)
        v.authorName.text = entity.author!!.name
        v.createTime.text = TimeUtils.millis2String(entity.createTime)
        v.detailValues.text = entity.feeds_text
        v.detailTag.text = entity.activityText
        //添加emojifragment到底部布局
        supportFragmentManager.beginTransaction().add(
            R.id.emoji_frame,
            FaceFragment.Instance()
        ).commit()
    }

    override fun bindLayout(): Int {
        return R.layout.activity_detail
    }

    override fun initData() {
        vm.commentsBus.observe(this, {
//            Log.e("ZXY","DetailActivity->"+it.data!!.size)
//            v.detailCoord.requestLayout()
            commentsAdapter.addData(0,it.data!!)
            val manager : LinearLayoutManager = v.detailComments.layoutManager as LinearLayoutManager
            manager.scrollToPosition(0)
//            Log.e("ZXY","DetailActivity->"+commentsAdapter.itemCount)

        })
        vm.initData(0, entity.itemId, entity.author!!.userId)
    }

    override fun onClick(v: View?) {
        if (R.id.detail_close == v!!.id){
            finish()
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        var index = 0
        //暂停列表中全部IJKVideoView
        while (index < commentsAdapter.itemCount) {
            if (commentsAdapter.getItem(index).commentType == 3){
                val ijk : IJKView = commentsAdapter.getViewByPosition(
                    index,
                    R.id.detail_item_player
                ) as IJKView
                ijk.relase()
            }
            index++
        }
        val videoIcon = commentsAdapter.getViewByPosition(position, R.id.video_icon)
        videoIcon!!.visibility = View.GONE
        val ijk : IJKView = commentsAdapter.getViewByPosition(position, R.id.detail_item_player) as IJKView
        ijk.setPath(commentsAdapter.getItem(position).videoUrl)
    }

    override fun onEmojiDelete() {
        val text: String = v.inputView.getText().toString()
        if (text.isEmpty()) {
            return
        }
        if ("]" == text.substring(text.length - 1, text.length)) {
            val index = text.lastIndexOf("[")
            if (index == -1) {
                val action = KeyEvent.ACTION_DOWN
                val code = KeyEvent.KEYCODE_DEL
                val event = KeyEvent(action, code)
                v.inputView.onKeyDown(KeyEvent.KEYCODE_DEL, event)
                try {
                    EmojiUtil.handlerEmojiText(
                        v.inputView,
                        v.inputView.getText().toString(),
                        this
                    )
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                return
            }
            v.inputView.getText().delete(index, text.length)
            try {
                EmojiUtil.handlerEmojiText(v.inputView, v.inputView.getText().toString(), this)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return
        }
        val action = KeyEvent.ACTION_DOWN
        val code = KeyEvent.KEYCODE_DEL
        val event = KeyEvent(action, code)
        v.inputView.onKeyDown(KeyEvent.KEYCODE_DEL, event)
        try {
            EmojiUtil.handlerEmojiText(v.inputView, v.inputView.getText().toString(), this)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onEmojiClick(emoji: Emoji?) {
        if (emoji != null) {
            val index: Int = v.inputView.getSelectionStart()
            val editable: Editable = v.inputView.getEditableText()
            if (index < 0) {
                editable.append(emoji.content)
            } else {
                editable.insert(index, emoji.content)
            }
            try {
                EmojiUtil.handlerEmojiText(v.inputView, v.inputView.getText().toString(), this)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

}